package com.yangml.demoqx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yangml.demoqx.entity.Role;
import com.yangml.demoqx.entity.User;
import com.yangml.demoqx.mapper.RoleMapper;
import com.yangml.demoqx.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",username);
        List<GrantedAuthority> authorities = new ArrayList<>();
        User user = Optional.ofNullable(userMapper.selectOne(wrapper))
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));

        List<Role> roles = roleMapper.getRoleCodes(user.getUserId());
        for (Role role:roles){
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleCode()));
        }
        return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getUserPwd(),authorities);
    }
}
